<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Index extends Common
{
    public function _initialize(){
        parent::_initialize();
    }
    
    public function index()
    {
        //分类ID
        $cateid = $this->request->param('cateid');
        $pid  = Db('arctype')->where('id',$cateid)->value('pid');
        // if ($pid==0) {
        //     $pid = $cateid;
        // }

        //分类
        $cates = Db('arctype')->where('status','1')->where('pid','0')->select();
        //小分类
        if ($pid) {
            $m_cates = Db('arctype')->where('status','1')->where('pid',$pid)->select();
        }else{
            $m_cates = Db('arctype')->where('status','1')->where('pid',$cateid)->select();
        }

        //产品
        if ($cateid) {
            $where['typeid'] = $cateid;
        }
        $products = Db('archive')->where($where)->paginate(9);



        $this->assign('cates',$cates);
        $this->assign('pid',$pid);
        $this->assign('cateid',$cateid);
        $this->assign('m_cates',$m_cates);
        $this->assign('products',$products);
        $this->assign('total',$products->total());
        $this->assign('page',$products->render());
        return $this->fetch();
    }
    
    /**
     * 产品详细页
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $product = Db('archive')->alias('a')->join('addonarticle d','d.aid=a.id')->where('a.id',$id)->where('status',1)->field('a.*,d.content')->find();

        $cates = Db('arctype')->where('status','1')->where('pid','0')->select();
        $cate_name  = Db('arctype')->where('id',$product['typeid'])->value('typename');

        $abouts = Db('archive')->where('typeid',$product['typeid'])->limit(6)->select();

        $this->assign('cates',$cates);
        $this->assign('cate_name',$cate_name);
        $this->assign('product',$product);
        $this->assign('abouts',$abouts);
        return $this->fetch();
    }
    
    /**
     * 创建订单
     */
    public function addorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $data['uid'] = session('user.id');
            $data['order_id'] = date('Ymd').time().rand(1,9);
            $price = Db('archive')->where('id',$data['pid'])->value('price');
            $data['total'] = $data['number']*$price;
            $data['create_time'] = time();
            $data['price'] = $price;
            $result = Db::name('order')->insert($data);
            if ($result) {
                return  Db::name('order')->getLastInsID();
            }
            return -1;
        }else{
            return -1;
        }
        


    }

    /**
     * 创建订单
     */
    public function order()
    {
        $this->checklogin();
        $id = $this->request->param('id');
        $order = Db('order')
        ->alias('o')
        ->join('tf_archive t','t.id = o.pid')
        ->field('o.*,t.title,t.litpic,t.description')
        ->where('o.id',$id)
        ->where('o.status',0)
        ->find();
        $this->assign('order',$order);
        return $this->fetch();
    }

     /**
     * 创建订单
     */
    public function changeorder()
    {
        if ($this->request->isPost()) {
             $id = $this->request->param('id');
             $type = $this->request->param('type');
             $number = $this->request->param('number');
             $number<=1 && $number=1;
             $price = Db('order')->where('id',$id)->value('price');
             $result = Db('order')->where('id',$id)->update(['number'=>$number,'total'=>$number*$price]);
             //var_dump(Db('order')->getLastSql());die;
             if ($result!==false) {
                 return  json(['status'=>1,'total'=>$number*$price,'number'=>$number]);
             }
             return json(['status'=>-1]);
        }else{
             return json(['status'=>-1]);
        }
    }
    
    /**
     * 支付订单
     */
    public function pay(){
        $this->checklogin();
        $id = $this->request->param('id');
        $data['pay_type'] = $this->request->param('pay_type');
        $data['operation'] = $this->request->param('operation');
        $data['assistant'] = $this->request->param('assistant');
        $data['remark'] = $this->request->param('remark');
        $result = Db('order')->where('id',$id)->update($data);
        if ($result!==false) {
            //微信支付
            if ($data['pay_type']==1) {
                return json(['status'=>1,'url'=>url('/weixin/'.$id)]);
            }
            //支付宝
            if ($data['pay_type']==2) {
                return json(['status'=>1,'url'=>url('/aplay/'.$id)]);
            }
            //现金
            if ($data['pay_type']==3) {
                // $data = Db('order')->where('id',$id)->find();
                // $this->addMoney($data['uid'],$data['id']);
                // $this->addScore($data['uid'],$data['id']);
                // $this->changeVolume($data['id']);
                //Db('order')->where('id',$id)->update(['status'=>1]);
                return json(['status'=>1,'url'=>url('/success/'.$id)]);
            }
        }

    }

    /**
     * 支付宝
     */
    public function aplay()
    {
        $id = $this->request->param('id');
        $data = Db('order')->where('id',$id)->find();
        exit('此支付方式尚未开通');
        var_dump($data);
        //return $this->fetch();
    }

    /**
     * 微信支付
     */
    public function weixin()
    {
        $id = $this->request->param('id');
        $data = Db('order')->where('id',$id)->find();
        $data['title'] = Db('archive')->where('id',$data['pid'])->value('title');
        //return $this->fetch();
        ini_set('date.timezone','Asia/Shanghai');
        //error_reporting(E_ERROR);
        require_once EXTEND_PATH."/wxpay/lib/WxPay.Api.php";

        require_once EXTEND_PATH."/wxpay/example/WxPay.NativePay.php";
        require_once EXTEND_PATH.'/wxpay/example/log.php';

        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("商品购买");
        $input->SetAttach("商品购买");
        $input->SetOut_trade_no($data['order_id']);
        $input->SetTotal_fee($data['total']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(url('/wxnotify'));
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($data['pid']);
        $result = $notify->GetPayUrl($input);
        $url2 = $result["code_url"];

        $this->assign('url2',$url2);
        $this->assign('data',$data);

        return $this->fetch('wxpay'); 
    }


    /**
     * 支付回调
     */
    public function wxnotify(){
        $order_id = $this->request->param('order_id');

        ini_set('date.timezone','Asia/Shanghai');
        error_reporting(E_ERROR);
        require_once EXTEND_PATH."/wxpay/lib/WxPay.Api.php";
        require_once EXTEND_PATH.'/wxpay/example/log.php';
        $input = new \WxPayOrderQuery();
        $input->SetOut_trade_no($order_id);
        $weixinback = \WxPayApi::orderQuery($input);
        
        if ($weixinback['trade_state']=='SUCCESS') {
            $data = Db('order')->where('order_id',$order_id)->find();
            $this->addMoney($data['uid'],$data['id']);
            $this->addScore($data['uid'],$data['id']);
            $this->changeVolume($data['id']);
            Db('order')->where('order_id',$order_id)->update(['status'=>1]);
            return json(['status'=>1,'id'=>$data['id']]);
        }
    }

    /**
     * 支付成功
     */
    public function success()
    {
        $this->checklogin();
        $id = $this->request->param('id');
        $data = Db('order')->where('id',$id)->find();

        $this->assign('data',$data);
        return $this->fetch();
    }
    
    /**
     * 支付成功后逻辑处理
     * 给美容店返现
     */
    public function addMoney($uid,$order_id){
        $config = Db('config')->where('type','backsalon')->select();
        $config = array_column($config,'v','k');
        $parent = Db('user')->where('id',$uid)->value('parent');
        $order  = Db('order')->where('id',$order_id)->find();
        if (!$parent)return true;
        $pid = Db('user')->where('id',$uid)->value('pid');
        $level = Db('user')->where('id',$parent)->value('level');
        //一级用户
        if ($pid==0) {
            if ($level==1) {
                $data['pay']   = $order['total']*$config['userone_to_a']/100;
            }
            if ($level==2) {
                $data['pay']   = $order['total']*$config['userone_to_b']/100;
            }
            if ($level==3) {
                $data['pay']   = $order['total']*$config['userone_to_c']/100;
            }
        }else{
            if ($level==1) {
                $data['pay']   = $order['total']*$config['usertwo_to_a']/100;
            }
            if ($level==2) {
                $data['pay']   = $order['total']*$config['usertwo_to_b']/100;
            }
            if ($level==3) {
                $data['pay']   = $order['total']*$config['usertwo_to_c']/100;
            }
        }
            $data['uid']       = $parent;
            $data['in_or_out'] = 1;
            $data['type']      = 1;
            $data['remak']     = '商品购买返现';
            //var_dump($data);die;
            $this->addLong($data);
            $data['uid']       = $uid;
            $data['in_or_out'] = 2;
            $data['remak']     = '商品购买消费';
            $data['pay']       = $order['total'];
            $this->addLong($data);

        //转介绍
        $pid =  Db('user')->where('id',$parent)->value('parent'); 
        if ($pid) {
            $data['uid']       = $pid;
            $data['in_or_out'] = 1;
            $data['type']      = 1;
            $data['remak']     = '转介绍返现';
            $level = Db('user')->where('id',$parent)->value('level');
            if ($level==1) {
                $data['pay']   = $order['total']*$config['introduce_a']/100;
            }
            if ($level==2) {
                $data['pay']   = $order['total']*$config['introduce_b']/100;
            }
            if ($level==3) {
                $data['pay']   = $order['total']*$config['introduce_c']/100;
            }
            $this->addLong($data);
        }
    }

    /**
     * 消费返积分
     */
    public function addScore($uid,$order_id)
    {
        $config = Db('config')->where('type','backscore')->select();
        $config = array_column($config,'v','k');
        $order  = Db('order')->where('id',$order_id)->find();

        $data['uid']       = $uid;
        $data['in_or_out'] = 1;
        $data['type']      = 2;
        $data['remak']     = '消费返积分';
        $data['pay']   = $order['total']*$config['user_score']/100;
        $this->addLongScore($data);

        $pid = Db('user')->where('id',$uid)->value('pid');
        if ($pid) {
            $data['uid']       = $pid;
            $data['in_or_out'] = 1;
            $data['type']      = 2;
            $data['remak']     = '下级消费返积分';
            $data['pay']   = $order['total']*$config['usertwo_to_user']/100;
            $this->addLongScore($data);
        }
    }

    /**
     * 增加用户资金 积分明细
     * $uid,$in_or_out,$pay,$type,$remak
     */
    public function addLong($data)
    {   
    
        if ($data['in_or_out']==1) {
            Db('user')->where('id',$data['uid'])->setInc('money',$data['pay']);
        }
        $data['create_time'] = time();
        Db('long')->insert($data);
    }

    /**
     * 增加用户积分明细
     * $uid,$in_or_out,$pay,$type,$remak
     */
    public function addLongScore($data){
       if ($data['in_or_out']==1) {
            Db('user')->where('id',$data['uid'])->setInc('score',$data['pay']);
        }else{
            Db('user')->where('id',$data['uid'])->setDec('score',$data['pay']);
        }
        $data['create_time'] = time();
        Db('long')->insert($data);
    }

    /**
     * 更改商品销量
     */
    public function changeVolume($order_id){
        return   Db('archive')->where('id',$order_id)->setInc('volume');
    }
}
